import axios, {
  type AxiosInstance,
  type AxiosResponse,
  type InternalAxiosRequestConfig
} from 'axios'
import { ElMessage } from 'element-plus'
import { localCache } from './cache'
import router from '@/router'

const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_SERVE,
  timeout: 5000
})

service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const token = localCache.get('token')
  if (token) {
    config.headers['token'] = token
  }

  return config
})

service.interceptors.response.use(
  (resp: AxiosResponse) => {
    const { code, message, data } = resp.data
    if (code === '00000') {
      return data
    } else {
      ElMessage({
        message,
        type: 'error'
      })
      return Promise.reject(resp.data)
    }
  },
  (error) => {
    let message = ''
    const status = error.response.status
    switch (status) {
      case 401:
        message = 'TOKEN过期'
        localCache.clear()
        router.push('/login')
        break
      case 403:
        message = '无权访问'
        break
      case 404:
        message = '请求地址错误'
        break
      case 500:
        message = '服务器异常'
        break
      default:
        message = '网络异常'
        break
    }

    ElMessage({
      type: 'error',
      message
    })
    return Promise.reject(error)
  }
)

export default service
